<template>
  <div class="ca">
    <!-- 顶部提示 -->
    <transition name="fadeIn">
      <div v-show="!isDrawn" class="hint-label" v-html="signer.hint"></div>
    </transition>

    <!-- 签字区 -->
    <div id="container" onmousedown="return false;">
      <canvas id="anysignCanvas" width="2" @isDrawn="updateIsDrawn"></canvas>
    </div>

    <!-- 底部按钮组 -->
    <div class="btn-wrap">
      <button class="theme-btn clear" @click="clear">清除</button>
      <button
        class="theme-btn confirm"
        :class="{ disabled: !this.isDrawn }"
        @click="confirm"
      >
        确认
      </button>
      <!-- 返回 -->
      <img
        class="icon"
        src="@/assets/imgs/global/icon/icon_ca_back.png"
        @click="back"
      />
    </div>

    <!--保留这部分 display:none 的 html，是因为签名供应商北京CA提供的前台代码耦合了页面元素（id) ^-^ -->
    <div id="dialog" style="display:none;">
      <div id="anysign_title" style="display:none;"></div>
      <div id="single_scrollbar" style="display:none;">
        <span id="single_scroll_text">*滑动操作：</span>
        <input
          id="single_scrollbar_up"
          type="button"
          class="button orange"
          value="左移"
        />
        <input
          id="single_scrollbar_down"
          type="button"
          class="button orange"
          value="右移"
        />
      </div>
      <div id="btnContainerOuter" style="display:none;"></div>
    </div>
  </div>
</template>

<script>
import * as sign from "@/assets/libs/CA";
import { mapState } from "vuex";

export default {
  name: "ca",
  data() {
    return {
      apiInstance: null, // 签字api对象
      isDrawn: false // 是否已经进行签字
    };
  },
  computed: {
    ...mapState({
      signer: state => state.global.signer // 当前签字对象
    })
  },
  mounted() {
    // 初始化API，并注册回调函数
    this.init();
    // 设置签字模板数据
    this.setTemplateData();
    // 检查API是否初始化和设置成功
    this.checkApi();
  },
  methods: {
    // 更新书写状态
    updateIsDrawn() {
      this.isDrawn = sign.isDrawn;
    },
    // 错误信息提示
    tipsError(msg) {
      utils.ui.tips({
        type: "error",
        msg: msg
      });
    },

    // 初始化API，并注册回调函数
    init() {
      // 修复华为浏览器底部被顶上去，强制往下滑动1px
      setTimeout(() => {
        window.scrollTo(0, utils.ui.getScrollTop() + 1);
      }, 500);

      // 设置签名算法，默认为RSA，可以设置成SM2
      sign.EncAlgType.EncAlg = "SM2";
      // 初始化签字api对象
      this.apiInstance = new sign.AnySignApi();

      let res;

      // 1: 初始化签名接口
      // 回调函数，签名确认后调用
      // eslint-disable-next-line
      const callback = (context_id, context_type, val) => {
        // 生成签名加密数据
        const uploadData = this.apiInstance.getUploadDataGram();
        // 签字图片
        const imgSrc = "data:image/png;base64," + val;
        // 触发signed事件，回传结果
        this.$eventBus.$emit("signed", {
          context_id: this.signer.context_id,
          uploadData,
          imgSrc
        });
        // 页面返回
        this.back();
      };
      // 根据回调函数和渠道号初始化signApi
      // 渠道号写死11111111
      res = this.apiInstance.initAnySignApi(callback, "11111111");
      if (!res) {
        this.tipsError("初始化签名接口失败");
        return;
      }

      // 2: 添加单签签名框
      res = this.addSignatureObj();
      if (!res) {
        this.tipsError("添加单签签名框失败");
        return;
      }

      // 3:将配置提交
      res = this.apiInstance.commitConfig();
      if (!res) {
        this.tipsError("提交签字配置失败");
      }
    },
    // 设置签字模板数据
    setTemplateData() {
      const formData = "xss"; //C写死xss
      const businessId = "123"; //集成信手书业务的唯一标识
      const template_serial = "xss"; //用于生成PDF的模板ID

      //配置JSON格式签名原文
      /**
       * 设置表单数据，每次业务都需要set一次
       * @param template_type 签名所用的模板类型
       * @param contentUtf8Str 表单数据，类型为Utf8字符串
       * @param businessId 业务工单号
       * @param template_serial 模板序列号
       * @returns {*} 是否设置成功
       */
      const res = this.apiInstance.setTemplate(
        sign.TemplateType.PDF,
        formData,
        businessId,
        template_serial
      );
      if (!res) {
        this.tipsError("设置签字模板数据失败");
      }

      return res;
    },
    // 检查API是否初始化和设置成功
    checkApi() {
      const RESULT_OK = 0,
        // RESULT_ERROR = -1,
        EC_API_NOT_INITED = 1,
        EC_WRONG_CONTEXT_ID = 2,
        // EC_CAMERA_INIT_FAILED = 3,
        // EC_NATIVE_EXCEPTION = 4,
        // EC_DEVICE_NOT_SUPPORTED = 5,
        EC_TEMPLATE_NOT_SET = 6;
      // EC_COMMENT_ALREADY_SHOW = 7;
      if (!this.apiInstance) {
        this.tipsError("信手书接口没有初始化");
        return;
      }

      const status = this.apiInstance.showSignatureDialog(
        this.signer.context_id
      );
      console.log("status: ", status);
      switch (status) {
        case RESULT_OK:
          console.log("初始化完毕");
          break;
        case EC_API_NOT_INITED:
          this.tipsError("信手书接口没有初始化");
          break;
        case EC_WRONG_CONTEXT_ID:
          this.tipsError("没有配置相应context_id的签字对象");
          break;
        case EC_TEMPLATE_NOT_SET:
          this.tipsError("EC_TEMPLATE_NOT_SET");
          break;
      }
    },

    //添加单签签名框
    addSignatureObj() {
      // 获取签字对象信息
      const context_id = this.signer.context_id;
      const custName = this.signer.custName;
      const identificationNumber = this.signer.identificationNumber;
      const keyword = this.signer.keyword;

      const signer = new sign.Signer(custName, identificationNumber);
      const signerRule = new sign.SignRule_KeyWordV2(keyword, 70, 20, 1, 1);

      const signatureConfig = new sign.SignatureConfig(signer, signerRule);
      //1:时间在上、2：时间在下、3：时间在右
      //		var timeTag = new TimeTag(1, "yyMMdd hh:mm;ss");
      //		signatureConfig.timeTag = timeTag;
      signatureConfig.singleWidth = 200;
      signatureConfig.singleHeight = 200;
      signatureConfig.title = keyword;
      signatureConfig.titleSpanFromOffset = 4;
      signatureConfig.titleSpanToOffset = 5;
      signatureConfig.penColor = "black";
      signatureConfig.isTSS = false; //是否开始时间戳服务
      signatureConfig.signatureImgRatio = 3.0;
      //		signatureConfig.nessesary = true;
      signatureConfig.isdistinguish = false;

      const res = this.apiInstance.addSignatureObj(context_id, signatureConfig);

      return res;
    },

    //清除签名
    clear() {
      sign.clear_canvas();
    },
    //确认签名
    confirm() {
      sign.sign_confirm();
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.ca {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-color: white;
  .hint-label {
    position: absolute;
    top: 15px;
    width: 100%;
    font-size: 20px;
    color: #4b4b4b;
    line-height: 30px;
    text-align: center;
    z-index: 1;
  }
  .btn-wrap {
    @include display-flex;
    position: fixed;
    bottom: 0px;
    width: 100%;
    background-color: white;
    box-shadow: 0 0 10px 0 #babec6;
    z-index: 1;
    .theme-btn {
      margin: 20px;
      width: 140px;
      &.clear {
        margin-right: 0;
        border-radius: 19px 0 0 19px;
        background-color: #c8cbd2;
      }
      &.confirm {
        margin-left: 0;
        border-radius: 0px 19px 19px 0;
      }
    }
    .icon {
      width: 30px;
      height: auto;
    }
  }
}
</style>
